package jvs.peer.xmpp;

import java.io.IOException;
import java.io.OutputStream;

import jvs.peer.net.PeerAddress;
import jvs.peer.sec.User;
import jvs.sh.CommandInterpreter;
import jvs.sh.Console;

public class XmppFileShell extends Shell {
	class MyConsole implements Console {

		public OutputStream data() {
			return out;
		}

		public void err(String s) {
			print("500 " + s);
		}

		public void input(String s) {
			ci.parse(s);
		}

		public void log(String s) {
			
		}

		public void ok(String s) {
			print("200 " + s);
		}

		public void out(String s) {
			print(s);
		}

		private void print(String s) {
			try {
				out.write(s.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public void status(String code, String s) {
			print(code+" "+s);
		}
	}

	private MyConsole console;
	private CommandInterpreter ci;
	private PeerAddress remoteAddress;
	private PeerAddress localAddress;
	private OutputStream out;

	public void setOut(OutputStream out) {
		this.out = out;
	}

	public XmppFileShell(PeerAddress local, PeerAddress remote) {
		this.localAddress = local;
		this.remoteAddress = remote;
	}

	public void init() {
		ci = new CommandInterpreter(null);
		console = new MyConsole();
		ci.setShell(this);
		ci.setConsole(console);
		//
	}

	public void abort() throws Exception {
	}

	public User getUser() {
		return new User(remoteAddress.getId(), remoteAddress.getResource());
	}

	public PeerAddress getRemoteAddress() {
		return remoteAddress;
	}

	public PeerAddress getLocalAddress() {
		return localAddress;
	}

	public boolean isConnected() {
		return true;
	}

	public void parse(String s) {
		ci.parse(s);
	}

	public void exit() {
		try {
			out.close();
		} catch (Exception e) {
			//
		}
	}
}
